package logic

import (
	"context"
	"errors"
	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"
	"fresh-box/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshCreateLogic {
	return &FreshCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建
func (l *FreshCreateLogic) FreshCreate(in *freshrpc.FreshCreateRequest) (*freshrpc.FreshCreateResponse, error) {
	// todo: add your logic here and delete this line

	var fresh mysql.Fresh
	mysql.DB.Debug().Where("name=?", in.Name).First(&fresh)
	if fresh.ID > 0 {
		return nil, errors.New("商品已存在")
	}
	tx := mysql.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	var category mysql.Category
	if err := tx.Debug().Where("category=?", category).Error; err != nil {
		category = mysql.Category{
			Name: in.Name,
		}
		tx.Rollback()
	}
	if err := category.CategoryCreate(mysql.DB); err != nil {
		tx.Rollback()
		return nil, err
	}
	fresh = mysql.Fresh{
		Name:       in.Name,
		Price:      float64(in.Price),
		Image:      in.Image,
		CategoryId: int64(category.ID),
	}

	if err := fresh.FreshCreate(mysql.DB); err != nil {
		tx.Rollback()
		return nil, err
	}
	if err := tx.Commit().Error; err != nil {
		return nil, err
	}
	return &freshrpc.FreshCreateResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
